#ifndef __REGEX_HPP__
#define __REGEX_HPP__

/**
 *  This file is part of PennerBot
 *
 *  Copyright (C) 2010 microkernel
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <iostream>

#include <boost/regex.hpp>
#include <boost/thread/recursive_mutex.hpp>

#include <core/convert.hpp>

namespace PBot
{
namespace Core
{
/**
 * Regular expression class using Boost::Regex
 */
class Regex
{
public:
    Regex(const std::string& expr);

    virtual ~Regex();

    template <class T>
    bool Search(const std::string& str, T& out)
    {
        boost::recursive_mutex::scoped_lock lock(mutex);

        if(!boost::regex_search(str, matches, this->regex))
        {
            return false;
        }

        if(matches.size() > 1)
        {
            out = StrToVar<T>(std::string(matches[1].first, matches[1].second));
            return true;
        }
        else
        {
            return false;
        }
    }

    bool Match(const std::string& str)
    {
        boost::recursive_mutex::scoped_lock lock(mutex);

        if(boost::regex_match(str, this->regex))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

private:
    /// Boost::Regex object
    boost::regex regex;

    /// Holds matches
    boost::smatch matches;

    boost::recursive_mutex mutex;
};

}
}

#endif // __REGEX_HPP__
